package com.study.talk.app.login.fragment;

import static androidx.navigation.fragment.FragmentKt.findNavController;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.study.talk.R;
import com.study.talk.app.base.BaseActivity;
import com.study.talk.app.base.BaseFragment;

import com.study.talk.app.home.HomeActivity;
import com.study.talk.app.login.LoginActivity;
import com.study.talk.databinding.FragmentSetUserInfoBinding;
import com.study.talk.entity.User;
import com.study.talk.entity.UserInfo;
import com.study.talk.entity.resp.RegisterHttpResponse;
import com.study.talk.entity.vo.UserInfoVo;
import com.study.talk.net.NetApi;
import com.study.talk.net.OkHttp;
import com.study.talk.netty.message.response.LoginResponse;
import com.study.talk.util.AppExecutor;
import com.study.talk.util.DateUtil;
import com.study.talk.util.FileUtil;
import com.study.talk.util.GsonInstance;
import com.study.talk.util.ToastUtil;
import com.study.talk.util.VerificationUtil;

import java.util.Calendar;

import io.netty.util.internal.StringUtil;

public class SetUserInfoFragment extends BaseFragment {


    private UserInfo userInfoRequest;
    private ActivityResultLauncher<Uri> takePhoto;
    private ActivityResultLauncher<PickVisualMediaRequest> selectPhoto;
    private FragmentSetUserInfoBinding fragmentSetUserInfoBinding;
    private LoginResponse loginResponse;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        assert getArguments() != null;
        loginResponse = GsonInstance.instance.fromJson(getArguments().getString("loginResponse", ""), LoginResponse.class);

        fragmentSetUserInfoBinding = FragmentSetUserInfoBinding.inflate(inflater, container, false);
        selectPhoto = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                uploadImage(FileUtil.getPathFromUri(requireContext(), uri));
            }
        });
        takePhoto = registerForActivityResult(new ActivityResultContracts.TakePicture(), result -> {
            if (result) {
                uploadImage(FileUtil.getPathFromUri(requireContext(), uri));
            }
        });
        return fragmentSetUserInfoBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        fragmentSetUserInfoBinding.registerPhone.setText(loginResponse.getUserInfo().getPhone());

        userInfoRequest = loginResponse.getUserInfo();
        userInfoRequest.setId(loginResponse.getUserId());
        userInfoRequest.setUsername(loginResponse.getUsername());

        fragmentSetUserInfoBinding.registerImg.setOnClickListener(v -> showSelectPhotoDialog(selectPhoto, takePhoto));

        fragmentSetUserInfoBinding.registerBirth.setOnClickListener(v -> {
            DatePickerDialog dialog = new DatePickerDialog(requireActivity());
            dialog.show();
            dialog.setOnDateSetListener((datePicker, year, month, day) -> {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, month);
                calendar.set(Calendar.DAY_OF_MONTH, day);
                userInfoRequest.setBirth(DateUtil.DateFormat.format(calendar.getTime()));
                fragmentSetUserInfoBinding.registerBirth.setText(userInfoRequest.getBirth());
            });
        });

        fragmentSetUserInfoBinding.registerBt.setOnClickListener(v -> {

            if (checkInput(fragmentSetUserInfoBinding.registerNickName, "请输入昵称")) return;
            if (checkInput(fragmentSetUserInfoBinding.registerPhone, "请输入手机号码")) return;
            if (checkInput(fragmentSetUserInfoBinding.registerEmail, "请输入邮箱")) return;
            if (checkInput(fragmentSetUserInfoBinding.registerAddress, "请输入住址")) return;
            if (checkInput(fragmentSetUserInfoBinding.registerIntroduce, "请输入简介")) return;

            if (userInfoRequest.getAvatar() == null || StringUtil.isNullOrEmpty(userInfoRequest.getAvatar())) {
                ToastUtil.showToast(requireContext(), "请上传头像");
            }


            if (!VerificationUtil.isValidEmailAddress(editTrim(fragmentSetUserInfoBinding.registerEmail))) {
                ToastUtil.showToast(requireContext(), "请输入正确的邮箱");
                return;
            }


            userInfoRequest.setNickName(editTrim(fragmentSetUserInfoBinding.registerNickName));
            userInfoRequest.setEmail(editTrim(fragmentSetUserInfoBinding.registerEmail));
            userInfoRequest.setAddress(editTrim(fragmentSetUserInfoBinding.registerAddress));
            userInfoRequest.setIntroduce(editTrim(fragmentSetUserInfoBinding.registerIntroduce));

            if (userInfoRequest.getBirth() == null) {
                ToastUtil.showToast(requireContext(), "请选择生日");
                return;
            }

            userInfoRequest.setGender(fragmentSetUserInfoBinding.genderGroup.getCheckedRadioButtonId() == R.id.register_man_bt ? 1 : 0);

            userInfoRequest.setBgImg("");

            /*String createTime = userInfoRequest.getCreateTime();
            userInfoRequest.setCreateTime(createTime);*/

            OkHttp.put("/userInfo/update", GsonInstance.instance.toJson(userInfoRequest), res -> {
                RegisterHttpResponse response = GsonInstance.instance.fromJson(res, RegisterHttpResponse.class);
                if (response.getStatus() == 200) {
                    loginResponse.setUserInfo(userInfoRequest);
                    AppExecutor.getInstance().MAIN_HANDLER().post(() -> {
                        ToastUtil.showToast(requireContext(), "信息初始化成功");
                        Bundle bundle = new Bundle();
                        bundle.putString("loginResponse", GsonInstance.instance.toJson(loginResponse));
                        findNavController(this).navigate(R.id.action_setUserInfoFragment_to_loadingFragment, bundle);
                    });
                } else {
                    AppExecutor.getInstance().MAIN_HANDLER().post(() -> ToastUtil.showToast(requireContext(), response.getMessage()));
                }
            });

        });
    }

    public void uploadImage(String path) {
        NetApi.uploadImage(path, (AppCompatActivity) requireActivity(), data -> {
            userInfoRequest.setAvatar(data);
            AppExecutor.getInstance().MAIN_HANDLER().post(() -> {
                Glide.with(this).load(OkHttp.URL + data).into(fragmentSetUserInfoBinding.registerImg);
                ToastUtil.showToast(requireContext(), "头像上传成功！");
            });
        }, msg -> AppExecutor.getInstance().MAIN_HANDLER().post(() -> ToastUtil.showToast(requireContext(), msg)));
    }
}